<template>
  <div class="ocr-container">
    <el-alert v-if="alertMessage" :title="alertMessage" :type="alertType" show-icon :closable="false" />
    <el-card class="header-card">
      <div class="header">
        <el-row :gutter="20">
          <!-- <el-col :span="4">
            <el-form-item label="年度">
              <el-input v-model="form.year" @change="updateTableData" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="责任者">
              <el-input v-model="form.responsibleParty" />
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="4">
            <el-form-item label="单位">
              <el-input v-model="form.socialSecurityUnit" />
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="4">
            <el-form-item label="案件编号">
              <el-input v-model="form.caseId" @change="updateTableData" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="盒号">
              <el-input v-model="form.boxId" @change="updateTableData" />
            </el-form-item>
          </el-col> -->
          <el-col :span="4">
            <el-upload class="upload-demo" action="" :auto-upload="false" :show-file-list="false"
              :on-change="handleFileChange">
              <el-button type="primary">上传扫描文件</el-button>
            </el-upload>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <el-card class="table-card">
      <div class="table-header">
        <div>
          <el-form :inline="true" :model="searchForm" class="demo-form-inline">
            <el-form-item label="姓名">
              <el-input v-model="searchForm.searchName" placeholder="输入名字自动筛选" clearable />
            </el-form-item>
            <el-form-item label="身份证号">
              <el-input v-model="searchForm.searchIdCard" placeholder="输入身份证号自动过滤" clearable />
            </el-form-item>
          </el-form>
        </div>
        <div class="table-actions">
          <el-checkbox v-model="sortByBox" @change="toggleSort">
            按盒号页号排序
          </el-checkbox>
          <el-button type="primary" @click="showExportOptions">导出数据</el-button>
        </div>
      </div>

      <el-table :data="showData" border style="width: 100%">
        <el-table-column prop="caseNumber" label="案件编号">
          <template #default="{ row, $index }">
            <el-input v-model="row.caseNumber" @keydown.enter.native="handleInputEnter($index, 0, $event)"
              :ref="(el: any) => setInputRef(el, $index, 0)" />
          </template>
        </el-table-column>
        <el-table-column prop="boxNumber" label="盒号">
          <template #default="{ row, $index }">
            <el-input v-model="row.boxNumber" @keydown.enter.native="handleInputEnter($index, 1, $event)"
              :ref="(el: any) => setInputRef(el, $index, 1)" />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名">
          <template #default="{ row, $index }">
            <el-input v-model="row.name" @keydown.enter.native="handleInputEnter($index, 2, $event)"
              :ref="(el: any) => setInputRef(el, $index, 2)" />
          </template>
        </el-table-column>
        <el-table-column prop="idCard" label="身份证">
          <template #default="{ row, $index }">
            <el-input v-model="row.idCard" @keydown.enter.native="handleInputEnter($index, 3, $event)"
              :ref="(el: any) => setInputRef(el, $index, 3)" />
          </template>
        </el-table-column>
        <el-table-column prop="creationDate" label="日期">
          <template #default="{ row, $index }">
            <el-input v-model="row.creationDate" @keydown.enter.native="handleInputEnter($index, 4, $event)"
              :ref="(el: any) => setInputRef(el, $index, 4)" />
          </template>
        </el-table-column>
        <el-table-column prop="pageNumber" label="页号">
          <template #default="{ row, $index }">
            <el-input v-model="row.pageNumber" type="number" @keydown.enter.native="handleInputEnter($index, 5, $event)"
              :ref="(el: any) => setInputRef(el, $index, 5)" />
          </template>
        </el-table-column>
        <el-table-column prop="itemNumber" label="件号">
          <template #default="{ row, $index }">
            <el-input v-model="row.itemNumber" type="number" @keydown.enter.native="handleInputEnter($index, 6, $event)"
              :ref="(el: any) => setInputRef(el, $index, 6)" />
          </template>
        </el-table-column>
        <el-table-column prop="socialSecurityUnit" label="社保单位">
          <template #default="{ row, $index }">
            <el-input v-model="row.socialSecurityUnit" @keydown.enter.native="handleInputEnter($index, 7, $event)"
              :ref="(el: any) => setInputRef(el, $index, 7)" />
          </template>
        </el-table-column>
        <el-table-column prop="responsibleParty" label="责任人">
          <template #default="{ row, $index }">
            <el-input v-model="row.responsibleParty" @keydown.enter.native="handleInputEnter($index, 8, $event)"
              :ref="(el: any) => setInputRef(el, $index, 8)" />
          </template>
        </el-table-column>
        <el-table-column prop="note" label="备注">
          <template #default="{ row, $index }">
            <el-input v-model="row.note" @keydown.enter.native="handleInputEnter($index, 9, $event)"
              :ref="(el: any) => setInputRef(el, $index, 9)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button size="small" type="danger" @click="handleDelete(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <span>{{ getTableLength() }}</span>

    </el-card>
    <el-row :gutter="20" class="result-section">
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>OCR识别结果</span>
          </template>
          <el-input v-model="ocrText" type="textarea" :rows="10" placeholder="识别结果将显示在这里" />
          <el-button type="primary" @click="analysesOCRData">重新解析</el-button>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card v-show="showInfoDisplay">
          <template #header>
            <span>解析结果</span>
          </template>
          <div class="result-info">
            <span>数据统计：{{ currentData.length }}条记录</span>
            <el-select v-model="currentSortMode" @change="applySort" style="margin-left: 20px">
              <el-option label="不排序" value="0" />
              <el-option label="升序" value="1" />
              <el-option label="降序" value="2" />
            </el-select>
          </div>

          <el-table :data="currentData" border style="width: 100%">
            <el-table-column :label="idType" prop="number" />
            <el-table-column label="姓名" prop="name" />
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 导出选项对话框 -->
    <!-- <el-dialog v-model="exportDialogVisible" title="导出Excel设置">
      <el-form>
        <el-form-item label="布局模式">
          <el-radio-group v-model="exportLayout" @change="toggleExportLayout">
            <el-radio label="fixedExportCols">固定列数</el-radio>
            <el-radio label="fixedExportRows">固定行数</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="exportLayout === 'fixedExportCols'" label="列数">
          <el-input-number v-model="exportCols" :min="1" :max="10" />
          <span class="auto-calc">自动行数: {{ autoRows }}</span>
        </el-form-item>

        <el-form-item v-else label="行数">
          <el-input-number v-model="exportRows" :min="1" />
          <span class="auto-calc">自动列数: {{ autoCols }}</span>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="exportDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="doExportExcel">确认导出</el-button>
      </template>
    </el-dialog> -->
  </div>
</template>
<script setup lang="ts">
defineOptions({
  name: 'OCR'
})
import { ref, computed, onMounted, nextTick, toRaw, watch, h } from 'vue'
import { ElMessage } from 'element-plus'
import { saveAs } from 'file-saver';
import ExcelJS from 'exceljs';
import { postBatchMedicalRecords } from '@/api/medicalInsurance'

interface FormData {
  // year: string
  // responsibleParty: string
  // socialSecurityUnit: string
  // caseId: string
  // boxId: string
}

interface TableRow {
  index: number
  caseNumber: string
  boxNumber: string
  name: string
  idCard: string
  creationDate: string
  pageNumber: string
  itemNumber: string
  note: string
}

interface OCRDataItem {
  number: string
  name: string
}

// 表单数据
const form = ref<FormData>({
  // year: new Date().getFullYear().toString(),
  // responsibleParty: '',
  // socialSecurityUnit: '',
  // caseId: '',
  // boxId: ''
})

let displayedRowCount = ref(1); // 初始显示1行

// 表格数据
let tableData = ref<any[]>([])
const showData = computed(() => {
  return tableData.value.filter(item =>
    item.name.includes(searchForm.value.searchName) && item.idCard.includes(searchForm.value.searchIdCard)
  )
});

const searchForm = ref({
  searchName: '',
  searchIdCard: ''
})

// OCR相关数据
const ocrText = ref('')
const currentData = ref<OCRDataItem[]>([])
const originalData = ref<OCRDataItem[]>([])
const showInfoDisplay = ref(false)

// 排序相关
const currentSortMode = ref('0')
const sortByBox = ref(false)

// 导出相关
// const exportDialogVisible = ref(false)
const exportLayout = ref('fixedExportCols')
const exportCols = ref(1)
const exportRows = ref(20)
const autoRows = computed(() => Math.ceil(currentData.value.length / exportCols.value))
const autoCols = computed(() => Math.ceil(currentData.value.length / exportRows.value))

// 提示信息
const alertMessage = ref('')
const alertType = ref<'success' | 'error'>('success')

// ID类型
const idType = computed(() =>
  currentData.value.length > 0 && isValidIDCard(currentData.value[0].number)
    ? '身份证号'
    : '序号'
)

// 输入框引用
interface InputRef {
  focus: () => void;
  select: () => void;
  $el?: HTMLElement;
}

// 输入框引用存储
const inputRefs = ref<Record<number, Record<number, any>>>({});

// 设置输入框引用
const setInputRef = (el: any, rowIndex: number, colIndex: number) => {
  if (!el) return;

  if (!inputRefs.value[rowIndex]) {
    inputRefs.value[rowIndex] = {};
  }
  // 直接存储Element Plus输入框组件实例
  inputRefs.value[rowIndex][colIndex] = el;
};

// 处理回车事件
const handleInputEnter = (rowIndex: number, colIndex: number, event: KeyboardEvent) => {
  event.preventDefault();
  if (rowIndex < tableData.value.length - 1) {
    nextTick(() => {
      // 聚焦到新显示行的同一列
      const nextInput = inputRefs.value?.[rowIndex + 1]?.[colIndex]?.$el?.querySelector('input');
      if (nextInput) {
        nextInput.focus();
        nextInput.select();
      }
    });

    // 当前是最后显示的行，且还有更多数据未显示
    // if (rowIndex === (displayedRowCount.value || 1) - 1 &&
    //   rowIndex < tableData.value.length - 1) {

    //   // 增加显示行数
    //   if (!displayedRowCount.value) {
    //     displayedRowCount.value = 1;
    //   }
    //   displayedRowCount.value++;

    //   nextTick(() => {
    //     // 聚焦到新显示行的同一列
    //     const nextInput = inputRefs.value?.[rowIndex + 1]?.[colIndex]?.$el?.querySelector('input');
    //     if (nextInput) {
    //       nextInput.focus();
    //       nextInput.select();
    //     }
    //   });
    // }
    // // 如果不是最后显示的行，直接跳转到下一行同一列
    // else if (rowIndex < (displayedRowCount.value || 1) - 1) {
    //   nextTick(() => {
    //     const nextInput = inputRefs.value?.[rowIndex + 1]?.[colIndex]?.$el?.querySelector('input');
    //     if (nextInput) {
    //       nextInput.focus();
    //       nextInput.select();
    //     }
    //   });
  } else {
    ElMessage.primary(`您已到达最后一行`);
  }
};

// 处理表格回车事件（备用）
const handleTableEnter = (event: KeyboardEvent) => {
  // 可以在这里添加全局回车处理逻辑
}

// 初始化
onMounted(async () => {
  try {
    // 检查是否存在 electronAPI，如果不存在则使用模拟逻辑
    if (window.electronAPI) {
      const isRunning = await window.electronAPI.checkPortStatus(1224)
      if (isRunning) {
        showAlert('OCR应用已启动', 'success')
      } else {
        // const result = await window.electronAPI.openSoftware('E:\\Umi-OCR_Paddle_v2.1.5\\Umi-OCR.exe')
        const config = await window.electronAPI.getConfig()
        const OCR_PATH = config.OCR_PATH
        showAlert(OCR_PATH, 'success')
        if (!OCR_PATH || !OCR_PATH.umiOCRPath) {
          showAlert('OCR软件路径未配置，请在设置中配置后重试', 'error')
          return
        } else {
          const result = await window.electronAPI.openSoftware(OCR_PATH)
          console.log('OCR启动成功:', result)
          showAlert('OCR应用已就绪', 'success')
        }
      }
    } else {
      // Web 模式下的默认行为
      showAlert('Web模式: 使用在线OCR服务', 'success')
    }
  } catch (error) {
    console.error('OCR启动失败:', error)
    showAlert('OCR应用自动开启失败，请刷新后重试。如仍未解决，手动打开OCR软件，或联系开发者。', 'error')
  }
})

// 文件上传处理
const handleFileChange = (file: { raw: File }) => {
  const reader = new FileReader()
  reader.onload = async (e) => {
    const result = e.target?.result as string
    try {
      showAlert('正在调用OCR识别...', 'success')
      
      // 检查是否存在 electronAPI，如果不存在则使用模拟逻辑
      let response;
      if (window.electronAPI) {
        response = await window.electronAPI.runOCR({ imageData: result })
      } else {
        // Web 模式下的模拟逻辑
        showAlert('Web模式: 使用模拟OCR服务', 'success')
        response = await new Promise(resolve => {
          setTimeout(() => {
            resolve({
              data: [
                { text: '张三', end: '' },
                { text: '身份证: 110101199003076574', end: '' },
                { text: '李四', end: '' },
                { text: '身份证: 110101199003073917', end: '' }
              ]
            })
          }, 1000)
        })
      }

      if (response.data) {
        ocrText.value = response.data
          .map((item: { text: string; end: string }) => item.text + item.end + '\n')
          .join('')
        showAlert('OCR识别完成', 'success')
        analysesOCRData()
      } else {
        showAlert('OCR识别结果为空，请检查图片格式或内容', 'error')
      }
    } catch (error) {
      showAlert(`OCR识别失败: ${(error as Error).message}`, 'error')
    }
  }
  reader.readAsDataURL(file.raw)
}

// 解析OCR数据
const analysesOCRData = () => {
  try {
    originalData.value = parseOCRText(ocrText.value)
    currentData.value = [...originalData.value]
    console.log(currentData)
    tableData.value = currentData.value.map((item, index) => ({
      index,
      caseNumber: '0001',
      boxNumber: '001',
      name: item.name,
      idCard: item.number,
      creationDate: '',
      pageNumber: '',
      itemNumber: '',
      note: ''
    }))
    updateAutoNumbers()
    applySort()
    showInfoDisplay.value = true
    showAlert('数据解析成功！', 'success')
  } catch (error) {
    showAlert(`解析失败: ${(error as Error).message}`, 'error')
  }
}

// 应用排序
const applySort = () => {
  if (currentData.value.length === 0) {
    showAlert('没有可排序的数据', 'error')
    return
  }

  switch (currentSortMode.value) {
    case '0':
      currentData.value = [...originalData.value]
      break
    case '1':
      currentData.value.sort((a, b) => parseInt(a.number) - parseInt(b.number))
      break
    case '2':
      currentData.value.sort((a, b) => parseInt(b.number) - parseInt(a.number))
      break
  }
}

// 更新表格数据
const updateTableData = () => {
  tableData.value.forEach(item => {
    item.creationDate = item.creationDate
    item.caseNumber = item.caseNumber
    item.boxNumber = item.boxNumber
  })
}

// 更新自动编号
const updateAutoNumbers = () => {
  if (tableData.value.length > 0) {
    const currentCaseNumber = tableData.value[0].caseNumber || ''
    const currentBoxNumber = tableData.value[0].boxNumber || ''
    let currentPageNumber = 1
    let currentItemNumber = 1
    let prevPage = ''

    tableData.value.forEach((row) => {
      if (!row.caseNumber && currentCaseNumber) {
        row.caseNumber = currentCaseNumber
      }
      if (!row.boxNumber && currentBoxNumber) {
        row.boxNumber = currentBoxNumber
      }

      const pageKey = `${row.caseNumber}-${row.boxNumber}`
      if (pageKey !== prevPage) {
        currentPageNumber = 1
        currentItemNumber = 1
        prevPage = pageKey
      }

      row.pageNumber = padNumber(currentPageNumber, 3)
      row.itemNumber = padNumber(currentItemNumber)
      currentItemNumber++
      currentPageNumber++
    })
  }
}

// 切换排序方式
const toggleSort = () => {
  if (sortByBox.value) {
    tableData.value.sort((a, b) => {
      const boxDiff = parseInt(a.boxNumber) - parseInt(b.boxNumber);
      if (boxDiff !== 0) return boxDiff;
      return parseInt(a.pageNumber) - parseInt(b.pageNumber);
    }
    )
  } else {
    tableData.value.sort((a, b) => a.index - b.index)
  }
}

// 导出功能
const showExportOptions = () => {
  if (currentData.value.length === 0) {
    showAlert('请先解析数据', 'error')
    return
  }
  doExportExcel();
  // exportDialogVisible.value = true
}

// const toggleExportLayout = (mode: string) => {
//   exportLayout.value = mode === 'fixedExportCols' ? 'fixedExportCols' : 'fixedExportRows'
// }


const doExportExcel = async () => {
  try {
    // 1. 定义字段映射（保证顺序）
    const fieldMap = {
      title: '题名',
      documentNumber: '文号',
      creationDate: "形成日期",
      socialSecurityCode: '社保编码',
      socialSecurityUnit: '社保单位',
      caseNumber: "案件编号",
      boxNumber: "盒号",
      name: "姓名",
      idCard: "身份证",
      otherId: '其它身份证',
      responsibleParty: "责任人",
      itemNumber: "件号",
      pageNumber: "页号",
      pageCount: "页数",
      township: "乡镇",
      hospital: "医院",
      note: "备注"
    } as const;

    // 2. 创建 workbook 和 worksheet
    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet('Sheet1');

    // 3. 设置表头和数据行字体（Arial 10号）
    // ExcelJS 不支持 worksheet.properties.defaultFont，需分别设置
    // 表头字体在 columns 定义中设置，数据行字体在添加行时设置

    // 4. 设置列定义（一次性设置）
    worksheet.columns = Object.entries(fieldMap).map(([enKey, zhKey]) => ({
      header: zhKey,
      key: enKey,
      width: enKey === 'idCard' ? 20 : 10,
      style: { font: { name: 'Arial', size: 10 } } // 表头字体
    }));

    // 5. 处理并添加数据行
    const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))
    tableData.value.filter(item => item.creationDate && item.name && item.idCard).forEach((item, index) => {
      item.operatorId = userInfo.value.userId || null
      // 数据处理逻辑
      if (index < tableData.value.length - 1) {
        item.pageCount = tableData.value[index + 1].pageNumber - item.pageNumber;
      }
      // item.responsibleParty = form.value.responsibleParty;
      // item.socialSecurityUnit = form.value.socialSecurityUnit;

      // 创建新行数据
      const row = worksheet.addRow(
        Object.fromEntries(
          Object.keys(fieldMap)
            .filter(enKey => item[enKey] !== undefined)
            .map(enKey => [enKey, item[enKey]])
        )
      );

      // 设置数据行字体（可选）
      row.font = { name: 'Arial', size: 10 };
    });

    // 6. 导出文件（兼容浏览器和Node环境）
    const sheetName = '数据_exported_' + new Date().getTime().toString().slice(0, 10);

    if (typeof window === 'undefined') {
      // Node.js 环境
      await workbook.xlsx.writeFile(`${sheetName}.xlsx`);
    } else {
      // 浏览器环境
      const buffer = await workbook.xlsx.writeBuffer();
      saveAs(new Blob([buffer], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      }), `${sheetName}.xlsx`);
    }

    ElMessage.success(`"${sheetName}"导出成功`);
    showAlert('导出成功！', 'success');
  } catch (error) {
    console.log('导出失败:', error);
    ElMessage.error(`导出失败: ${error instanceof Error ? error.message : String(error)}`);
  }

  // 将数据保存到数据库
  try {
    const response = await postBatchMedicalRecords(tableData.value);
    if (response) {
      showAlert('数据已成功保存到数据库', 'success');
    } else {
      showAlert('数据保存到数据库失败', 'error');
    }
  } catch (error) {
    showAlert(`数据保存到数据库失败: ${(error as Error).message}`, 'error');
  }
};

const getTableLength = () => {
  const realCount = tableData.value.filter(item => item.name && item.idCard).length
  return tableData.value.length > 0 ? '共 ' + tableData.value.length + ' 条记录，有效数据 ' + realCount + ' 条' : ''
}

// 工具函数
const showAlert = (message: string, type: 'success' | 'error') => {
  alertMessage.value = message
  alertType.value = type
  setTimeout(() => {
    alertMessage.value = ''
  }, type === 'error' ? 5000 : 3000)
}

const isValidIDCard = (num: string): boolean => {
  return /^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/.test(num) ||
    /^[1-9]\d{7}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}$/.test(num)
}

const parseOCRText = (text: string): OCRDataItem[] => {
  const cleanedText = text.replace(/[√Vv×*#@¥$%^&\/]+/g, '')
    .replace(/\s+/g, ' ')
    .trim()

  const pattern = /([\u4e00-\u9fa5]{2,4})(?:\s*)([a-zA-Z0-9]{15,18})|([a-zA-Z0-9]{15,18})(?:\s*)([\u4e00-\u9fa5]{2,4})/g

  const pairs: OCRDataItem[] = []
  let matches: RegExpExecArray | null

  while ((matches = pattern.exec(cleanedText)) !== null) {
    if (matches[1] && matches[2]) {
      pairs.push({ name: matches[1], number: matches[2] })
    } else if (matches[3] && matches[4]) {
      pairs.push({ number: matches[3], name: matches[4] })
    }
  }

  const lines = text.split('\n').map(line => line.trim()).filter(line => line)
  let currentNumber: string | null = null

  for (const line of lines) {
    if (pairs.some(pair => line.includes(pair.number) || line.includes(pair.name))) {
      continue
    }

    if (/^[a-zA-Z0-9]{15,18}$/.test(line)) {
      currentNumber = line
      continue
    }

    if (/^[\u4e00-\u9fa5]{2,4}$/.test(line) && currentNumber) {
      pairs.push({ number: currentNumber, name: line })
      currentNumber = null
    }
  }

  if (currentNumber) {
    pairs.push({ number: currentNumber, name: '（未识别）' })
  }

  return pairs
}

const padNumber = (num: number, length: number = 3): string => {
  return num.toString().padStart(length, '0')
}

const handleDelete = (index: number) => {
  tableData.value.splice(index, 1);
  ElMessage.success('删除成功');
};
</script>

<style scoped>
.ocr-container {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-actions {
  display: flex;
  align-items: center;
  gap: 20px;
}

.result-section {
  margin-top: 20px;
}

.result-info {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.auto-calc {
  margin-left: 10px;
  font-style: italic;
  color: #666;
}

.upload-demo {
  display: inline-block;
}
</style>